package cn.loioi.web.controller.api;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.loioi.util.RequestUtil;
import cn.loioi.web.common.BaseJSONController;

@RestController
@RequestMapping("/api/upload.json")
public class FileUploadContorller extends BaseJSONController {
	private final static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 文件不存在
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	public Model uploadPOST(HttpServletRequest request, HttpServletResponse response, Model model) {
		return renderFail(model, "文件不存在");
	}

	/**
	 * 文件上传
	 * @param file
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	public Model upload(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (file == null) return renderFail(model, "文件不存在");
		try {
			// 获取存储目录
			String rootPath = request.getServletContext().getRealPath("/");
			String realPath = "/upload/" + df.format(new Date()) + "/";
			File path = new File(rootPath, realPath);
			if (!path.exists()) {
				path.mkdirs();
			}
			// 创建文件名
			String oldName = file.getOriginalFilename();
			String fileSuffix = oldName.substring(oldName.lastIndexOf("."));
			String fileName = RequestUtil.getValueStr(request, "md5", new String(DigestUtils.md5Digest(oldName.getBytes())));
			// 移动文件到上传目录
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path, fileName + fileSuffix));
			// 返回文件信息
			model.addAttribute("size", file.getSize());
			model.addAttribute("ContentType", file.getContentType());
			model.addAttribute("name", oldName);
			logger.debug("文件上传成功(size:{}/type:{}):{}", file.getSize(), file.getContentType(), oldName);
			return renderSuccess((realPath + fileName + fileSuffix), model);
		} catch (IOException e) {
			return renderFail(model, e.getMessage());
		}
	}
}
